package com.atguigu.gmallrealtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.atguigu.gmallrealtime.bean.CartAddUuBean;
import com.atguigu.gmallrealtime.common.Constant;
import com.atguigu.gmallrealtime.util.DateFormatUtil;
import com.atguigu.gmallrealtime.util.DorisUtil;
import com.atguigu.gmallrealtime.util.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * @author yhm
 * @create 2023-10-10 9:29
 */
public class DwsTradeCartAddUuWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1 创建flink环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // TODO 2 添加检查点和状态后端
        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);

        //2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //2.3 设置job取消之后 检查点是否保留
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //2.4 设置两个检查点之间最小的时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        //2.5 设置重启策略
        // env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,3000L));
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30), Time.seconds(3)));

        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");

        System.setProperty("HADOOP_USER_NAME","atguigu");

        // TODO 3 读取dwd_trade_cart_add主题数据
        String groupId = "dws_trade_cart_add_uu_window";
        KafkaSource<String> kafkaSource = MyKafkaUtil.getKafkaSource(Constant.TOPIC_DWD_TRADE_CART_ADD, groupId);
        DataStreamSource<String> cartAddSource = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "cart_add_source");

        // TODO 4 清洗过滤 转换为jsonObject
        SingleOutputStreamOperator<JSONObject> jsonObjectStream = cartAddSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(value);
                    out.collect(jsonObject);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

//        jsonObjectStream.print();

        // TODO 5 添加水位线
        SingleOutputStreamOperator<JSONObject> withWaterMarkStream = jsonObjectStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forMonotonousTimestamps().withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                return element.getLong("ts") * 1000;
            }
        }));

        // TODO 6 根据用户id分组
        KeyedStream<JSONObject, String> keyedStream = withWaterMarkStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject value) throws Exception {
                return value.getString("user_id");
            }
        });

        // TODO 7 使用状态判断是否为独立加购用户  同时转换为javaBean
        SingleOutputStreamOperator<CartAddUuBean> beanStream = keyedStream.map(new RichMapFunction<JSONObject, CartAddUuBean>() {
            ValueState<String> lastAddDtState = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> lastAddDtDes = new ValueStateDescriptor<>("last_add_dt", String.class);
                lastAddDtDes.enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1L)).build());
                lastAddDtState = getRuntimeContext().getState(lastAddDtDes);
            }

            @Override
            public CartAddUuBean map(JSONObject value) throws Exception {
                String lastAddDt = lastAddDtState.value();
                long ts = value.getLong("ts") * 1000;
                String curDt = DateFormatUtil.toDate(ts);
                String dorisDate = DateFormatUtil.toDorisDate(ts);
                // 加购独立用户数
                Long cartAddUuCt = 0L;
                if (lastAddDt == null || !lastAddDt.equals(curDt)) {
                    cartAddUuCt = 1L;
                    lastAddDtState.update(curDt);
                }
                return new CartAddUuBean("", "", dorisDate, cartAddUuCt, ts);
            }
        });

        // TODO 8 开窗聚合
        SingleOutputStreamOperator<CartAddUuBean> reduceStream = beanStream.windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10L))).allowedLateness(org.apache.flink.streaming.api.windowing.time.Time.seconds(5L))
                .reduce(new ReduceFunction<CartAddUuBean>() {
                    @Override
                    public CartAddUuBean reduce(CartAddUuBean value1, CartAddUuBean value2) throws Exception {
                        value1.setCartAddUuCt(value1.getCartAddUuCt() + value2.getCartAddUuCt());
                        return value1;
                    }
                }, new ProcessAllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>() {
                    @Override
                    public void process(Context context, Iterable<CartAddUuBean> elements, Collector<CartAddUuBean> out) throws Exception {
                        TimeWindow window = context.window();
                        String stt = DateFormatUtil.toYmdHms(window.getStart());
                        String edt = DateFormatUtil.toYmdHms(window.getEnd());
                        for (CartAddUuBean element : elements) {
                            element.setStt(stt);
                            element.setEdt(edt);
                            out.collect(element);
                        }
                    }
                });

//        reduceStream.print();

        // TODO 9 写出到doris
        reduceStream.map(new MapFunction<CartAddUuBean, String>() {
            @Override
            public String map(CartAddUuBean value) throws Exception {
                SerializeConfig config = new SerializeConfig();
                config.setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCase);
                return JSON.toJSONString(value, config);
            }
        })
                .sinkTo(DorisUtil.getDorisSink("dws_trade_cart_add_uu_window"));

        // TODO 10 执行任务
        env.execute();

    }
}
